package com.wiken.storeservice.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wiken.servicecommon.common.Code;
import com.wiken.servicecommon.common.TokenUtil;
import com.wiken.servicecommon.common.exception.DefaultException;
import com.wiken.storeservice.VO.UserStoreActivityVO;
import com.wiken.storeservice.entity.StoreActivity;
import com.wiken.storeservice.entity.UserStoreActivity;
import com.wiken.storeservice.mapper.UserStoreActivityMapper;
import com.wiken.storeservice.service.IUserStoreActivityService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Array;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wiken
 * @since 2023-02-08
 */
@Service
@Slf4j
public class UserStoreActivityServiceImpl extends ServiceImpl<UserStoreActivityMapper, UserStoreActivity> implements IUserStoreActivityService {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private StoreActivityServiceImpl storeActivityService;
    @Value("${properties.rocketmq.topic}")
    private String topic;

    boolean checkUser(String userId, String token){
        if(token == null) throw new DefaultException(Code.ERROR_AUTHORIZATION_NULL, "请重新登陆");

        Claims claims = TokenUtil.parseToken(token);

        if(claims == null) throw new DefaultException(Code.ERROR_AUTHORIZATION_NULL, "请重新登陆");

        String resultUserId = claims.get("userId", String.class);

        if(resultUserId == null) throw new DefaultException(Code.ERROR_AUTHORIZATION_NULL, "请重新登陆");

        if(!resultUserId.equals(userId)) throw new DefaultException(Code.ERROR_AUTHORIZATION, "认证失败，请重新登陆");

        return true;
    }

    @Override
    @Transactional
    public boolean addUserStoreActivity(UserStoreActivity userStoreActivity, String token) {
        StoreActivity storeActivity = storeActivityService.getById(userStoreActivity.getActivityId());

        //如果超过当前时间，那么这个优惠劵不用抢了
        if(storeActivity.getEndTime().isBefore(LocalDateTime.now())){
            throw new DefaultException(Code.ERROR_STORE_ACTIVITY_TIME_EXPIRE, "优惠劵已经过期");
        }

//        checkUser(userStoreActivity.getUserId(), token);

        //将优惠劵状态设置为 未使用
        userStoreActivity.setStatus(1);

        String storeActivityId = userStoreActivity.getActivityId();
        String userId = TokenUtil.getUserIdByToken(token);

        userStoreActivity.setUserId(userId);
        Map<String, String> params = new HashMap<>();
        params.put("activity_id", storeActivityId);
        params.put("user_id", userId);

        List<UserStoreActivity> resultList = baseMapper.selectList(new QueryWrapper<UserStoreActivity>().allEq(params));
        //如果result不等于null，说明用户已经领取了该优惠劵
        if(resultList.size() > 0) throw new DefaultException(Code.ERROR_USER_STORE_ACTIVITY_ADD, "该优惠劵不能重复领取");

        rocketMQTemplate.asyncSend(topic, JSON.toJSON(userStoreActivity), new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("发送优惠劵异步消息成功");
            }

            @Override
            public void onException(Throwable throwable) {
                log.error("发送优惠劵异步消息失败");
            }
        });

        return true;
    }

    @Override
    public ArrayList<UserStoreActivityVO> getUserStoreActivity(String token) {
        String userId = TokenUtil.getUserIdByToken(token);
        ArrayList<UserStoreActivityVO> userStoreActivityVOArrayList = baseMapper.getUserStoreActivity(userId);
        return userStoreActivityVOArrayList;
    }

    @Override
    public boolean useUserStoreActivity(String userStoreActivityId, String token) {

        UserStoreActivity userStoreActivity = baseMapper.selectOne(new QueryWrapper<UserStoreActivity>().eq("id", userStoreActivityId));

        userStoreActivity.setStatus(2);

        int success = baseMapper.updateById(userStoreActivity);

        //使用优惠劵需要修改用户当前优惠劵的状态
        return success > 0;
    }

    @Override
    public ArrayList<UserStoreActivityVO> getUserStoreActivityByStoreId(String storeId, String token) {
        String userId = TokenUtil.getUserIdByToken(token);
        ArrayList<UserStoreActivityVO> activityList = baseMapper.getUserStoreActivityByStoreId(storeId, userId);
        return activityList;
    }
}
